package com.zgs.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zgs.common.to.es.SkuEsModel;
import com.zgs.mall.search.config.MallElasticSearchConfig;
import com.zgs.mall.search.constant.EsConstant;
import com.zgs.mall.search.service.SearchServer;
import com.zgs.mall.search.vo.SearchParam;
import com.zgs.mall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServerImpl implements SearchServer {
    @Autowired
    private RestHighLevelClient esRestClient;
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchRequest searchRequest = createSearchRequest(searchParam);

        SearchResponse search=null;
        try{
             search = esRestClient.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);
        }catch (Exception e){
            e.printStackTrace();
        }
        SearchResult searchResult = buildSearchResult(search, searchParam);

        return searchResult;
    }
    //封装返回的数据
    public  SearchResult buildSearchResult(SearchResponse search,SearchParam searchParam){
        SearchResult searchResult =new SearchResult();
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        List<SkuEsModel> skuEsModel =new ArrayList<SkuEsModel>();
        if (hits1 !=null && hits1.length>0){
            for (SearchHit searchHit: hits1) {
                String sourceAsString = searchHit.getSourceAsString();
                SkuEsModel skuEsModel1 = JSON.parseObject(sourceAsString, SkuEsModel.class);
                skuEsModel.add(skuEsModel1);
            }
        }
        //商品数据
        searchResult.setProducts(skuEsModel);
        //分页相关
        searchResult.setPageNum(searchParam.getPageNum());
        long total =hits.getTotalHits().value;
        searchResult.setTotal(total);
        searchResult.setTotalPages(total%EsConstant.PAGE_SIZE==0?(int)total/EsConstant.PAGE_SIZE:((int)total/EsConstant.PAGE_SIZE+1));
        //聚合相关
        List<SearchResult.CatalogVo> catalogVos =new ArrayList<>();
        Aggregations aggregations = search.getAggregations();
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for ( Terms.Bucket bucket: buckets) {
            SearchResult.CatalogVo catalogVo =new SearchResult.CatalogVo();
            String cataId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.valueOf(cataId));
           ParsedStringTerms catalog_name_agg=bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);
        //品牌

        List<SearchResult.BrandVo> brandVos =new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> brandBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandBucket : brandBuckets) {
            SearchResult.BrandVo brandVo =new SearchResult.BrandVo();
            String keyAsString = brandBucket.getKeyAsString();
            brandVo.setBrandId(Long.valueOf(keyAsString));
            ParsedStringTerms brand_img_agg = brandBucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
            ParsedStringTerms brand_name_agg = brandBucket.getAggregations().get("brand_name_agg");
            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        //属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> buckets1 = attr_id_agg.getBuckets();
        for (Terms.Bucket bucket : buckets1) {
            SearchResult.AttrVo attrVo =new SearchResult.AttrVo();
            String keyAsString = bucket.getKeyAsString();
            attrVo.setAttrId(Long.valueOf(keyAsString));
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attr_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name);
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(b -> ((Terms.Bucket) b).getKeyAsString()).collect(Collectors.toList());
            attrVo.setAttrValue(collect);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
        return searchResult;
    }
    //创建es检索
    public SearchRequest createSearchRequest(SearchParam searchParam){
        //模糊匹配,过滤(按照属性,分类,品牌,价格区间,库存),排序,分页,高亮,聚合分析
        //检索条件DSL
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();

        /**
         * 模糊匹配,过滤(按照属性,分类,品牌,价格区间,库存)
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //must
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword());
            boolQueryBuilder.must(matchQueryBuilder);
        }
        //filter
        //分类
        if (searchParam.getCatalog3Id()!=null){
            TermQueryBuilder catalogId = QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id());
            boolQueryBuilder.filter(catalogId);
        }
        //品牌
        if (searchParam.getBrandId() !=null && searchParam.getBrandId().size()>0 ){
            TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("brandId", searchParam.getBrandId());
            boolQueryBuilder.filter(termsQueryBuilder);
        }
        //库存
        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock()==null?true:searchParam.getHasStock()==1?true:false));

        //价格区间 1_500/_500/500_
        if(!StringUtils.isEmpty(searchParam.getSkuPrice())){
            String[] split = searchParam.getSkuPrice().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (split.length==2){
                rangeQuery.lte(split[1]).gte(split[0]);
            }else{
                if (searchParam.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(split[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(split[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }

        //属性查询 nested
        if (searchParam.getAttrs() !=null && searchParam.getAttrs().size()>0){
            for (String attr: searchParam.getAttrs()) {
                //1_15寸:8寸
                String[] s = attr.split("_");
                String attrId= s[0];
                String[] attrValues = s[1].split(":");
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        sourceBuilder.query(boolQueryBuilder);
        /**
         * 排序
         *  sort=saleCount_asc/desc
         *  sort=skuPrice_asc/desc
         */
        String sort = searchParam.getSort();
        if (!StringUtils.isEmpty(sort)){
            String[] s = sort.split("_");
            if ("asc".equals(s[1])){
                sourceBuilder.sort(s[0], SortOrder.ASC);
            }else{
                sourceBuilder.sort(s[0], SortOrder.DESC);
            }

        }
        /**
         *分页,
         */
        sourceBuilder.from((searchParam.getPageNum()==null?1-1:searchParam.getPageNum()-1)*EsConstant.PAGE_SIZE);
        sourceBuilder.size(EsConstant.PAGE_SIZE);
        /**
         * 高亮
         */
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /**
         * 聚合分析
         */
        //品牌
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
        brand_name_agg.field("brandName").size(1);
        brand_agg.subAggregation(brand_name_agg);
        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg");
        brand_img_agg.field("brandImg").size(1);
        brand_agg.subAggregation(brand_img_agg);
        sourceBuilder.aggregation(brand_agg);
        //分类
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId");
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(1);
        attr_agg.subAggregation(attr_id_agg);
        attr_id_agg.subAggregation(AggregationBuilders.terms( "attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        sourceBuilder.aggregation(attr_agg);
        System.out.println(sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
        return  searchRequest;
    }
}
